package com.uniledger.exchange.model.rx;

import android.util.Log;

import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.R;
import com.uniledger.exchange.UniApp;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.functions.Consumer;

/**
 * Created by Weiss on 2017/2/9.
 */

public class RxException<T extends Throwable> implements Consumer<T> {

    private static final String TAG = "RxException";
    private Consumer<? super Throwable> onError;
    public RxException(Consumer<? super Throwable> onError) {
        this.onError = onError;
    }

    /**
     * Consume the given value.
     *
     * @param t the value
     * @throws Exception on error
     */
    @Override
    public void accept(T t) throws Exception {
        if (t instanceof SocketTimeoutException) {
            ToastUtils.show(UniApp.getInstance().getResources().getString(R.string.network_error_timeout));
            onError.accept(new Throwable(UniApp.getInstance().getResources().getString(R.string.network_error_timeout)));
        } else if (t instanceof ConnectException) {
            ToastUtils.show(UniApp.getInstance().getResources().getString(R.string.network_error_connect));
            onError.accept(new Throwable(UniApp.getInstance().getResources().getString(R.string.network_error_connect)));
        } else if (t instanceof UnknownHostException) {
            ToastUtils.show(UniApp.getInstance().getResources().getString(R.string.network_error_unknow_host));
            onError.accept(new Throwable(UniApp.getInstance().getResources().getString(R.string.network_error_unknow_host)));
        } else {
            onError.accept(t);
        }
    }
}
